# -*- coding: utf-8 -*-
"""
Created on Tue Nov 14 15:37:50 2017

@author: xuanlei
"""
import som_v1
import numpy as np
import matplotlib.pyplot as plt
from collections import Counter
import pandas as pd
import pre2

def st_f(df_o):

    df_p = df_o.iloc[:,:-1].diff().dropna(axis=0)
    df_p.index = range(df_p.shape[0])

    
    io_num = df_p.shape[1]
    sep_point = int(io_num/2)
    input_df = df_p.iloc[:,range(0,sep_point)]
    output_df = df_p.iloc[:, range(sep_point, io_num)]
    input_df_com = np.array(input_df)
    output_df_com = np.array(output_df)
    
    df = pd.DataFrame()
    sub_df = input_df_com-output_df_com 
    df['balance'] = list(np.abs(np.sum(input_df_com,axis=1)-np.sum(output_df_com, axis=1))/np.sum(input_df_com,axis=1))
    df['distance'] = np.sqrt(np.sum(np.square(sub_df), axis=1))
    
    df['min_input']=[input_df.iloc[i,:].min() for i in input_df.index]          #最小值
    df['max_input']=[input_df.iloc[i,:].max() for i in input_df.index]          #最大值
    df['mean_input']=[input_df.iloc[i,:].mean() for i in input_df.index]        #均值
    df['mad_input']=[input_df.iloc[i,:].mad() for i in input_df.index]          #根据均值计算平均绝对离差
    df['median_input']=[input_df.iloc[i,:].median() for i in input_df.index]    #中位数
    df['std_input']=[input_df.iloc[i,:].std() for i in input_df.index]
    
    df['min_output']=[output_df.iloc[i,:].min() for i in output_df.index]          #最小值
    df['max_output']=[output_df.iloc[i,:].max() for i in output_df.index]          #最大值
    df['mean_output']=[output_df.iloc[i,:].mean() for i in output_df.index]        #均值
    df['mad_output']=[output_df.iloc[i,:].mad() for i in output_df.index]          #根据均值计算平均绝对离差
    df['median_output']=[output_df.iloc[i,:].median() for i in output_df.index]    #中位数
    df['std_output']=[output_df.iloc[i,:].std() for i in output_df.index]
    
#    np_data = np.array(df)
    return df


def get_data(df):

    return df

def plot_map(som):
    plt.bone()
    plt.pcolor(som.distance_map().T)  # plotting the distance map as background
    plt.colorbar()
    plt.show()

def add_cluster_label(data,label,num):
    data = pd.DataFrame(data)
    data['cluster'] = label
    data['label_num'] = num
    data2 = data.sort_values(by='cluster')
    return data2

def som_cluster(data_name,d_x,d_y,sigma=0.5,lr=0.5):
    '''
     Parameters
        ----------
        data: list, original data
        d_x:int
            x dimension of the SOM

        d_y : int
            y dimension of the SOM
            
     '''
#    ex_list = []
    cluster_data = []
    try:
        
        for xx in data_name:
            l = []
            datax = get_data(globals()[xx])
            datax = st_f(datax)
            datax = np.array(datax)

            som = som_v1.MiniSom(d_x,d_y,datax.shape[1], sigma=sigma, learning_rate=lr) # initialization of d_x*d_y SOM
    #        print ("Training...NO.%d"%cnt)
            som.train_batch(datax, 100) # trains the SOM with 100 iterations
    #        print (".NO.%d..ready!"%cnt)
            for line in datax:
                l.append(som.winner(line))
            print('cluster num is %d'%(len(set(l))))
            print(set(l))
            
    #        clu_data = add_cluster_label(globals()[xx],l,len(set(l)))
    #        cluster_data.append(clu_data)
            print("now plotting the distance map-{} !".format(xx))
            
            plot_map(som)
    except:
        pass

#    return cluster_data
             
    
    

    
#pre2.regroup('data_ori.csv')  
cluster_data = som_cluster(data_name_list,100,100, sigma=1.0,lr=0.5)
    